package sk.hackcraft.multibox.server.net.servlet;

import org.json.JSONArray;
import org.json.JSONObject;

import sk.hackcraft.multibox.server.Library;
import sk.hackcraft.multibox.server.Song;
import sk.hackcraft.multibox.server.User;
import sk.hackcraft.multibox.server.net.Server;
import sk.hackcraft.multibox.server.net.UserServlet;
import sk.nixone.http.ServletExchange;

public class LibrariesServlet extends UserServlet {
	public LibrariesServlet(Server server) {
		super(server);
	}

	@Override
	public JSONObject doUserRequest(User user, Method method,
			ServletExchange exchange, JSONObject response) {
		
		JSONArray libraries = new JSONArray();
		JSONArray songs = new JSONArray();
		
		String idString = exchange.getQueryValue("id");
		if(idString == null) {
			for(Library lib : server.box.getRootLibraries()) {
				libraries.put(lib.toJSON());
			}
		} else {
			long id = Long.valueOf(exchange.getQueryValue("id"));
			Library lib = Library.all.get(id);
			
			if(lib.parent != null) {
				response.put("parent", lib.parent.toJSON());
			}
			
			for(Library subLib : lib.getLibraries()) {
				libraries.put(subLib.toJSON());
			}
			for(Song song : lib.getSongs()) {
				songs.put(song.toJSON());
			}
		}
		
		response.put("libraries", libraries);
		response.put("songs", songs);
		
		return response;
	}
}
